package org.iks.user.util;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.signers.PlainDSAEncoding;

/**
 * Author kzou
 * Date 2024/5/6
 * Description:
 */
public class SMUtil {

    public static String encryptHex(String hexPublicKey, String hexData) {
        SM2 sm2 = SmUtil.sm2(null, hexPublicKey);
        sm2.setEncoding(new PlainDSAEncoding());
        sm2.setMode(SM2Engine.Mode.C1C3C2);
        return sm2.encryptHex(hexData, KeyType.PublicKey);
    }
    public static String sign(String hexPrivateKey, String hexData) {
        SM2 sm2 = SmUtil.sm2(hexPrivateKey, null);
        sm2.setEncoding(new PlainDSAEncoding());
        sm2.setMode(SM2Engine.Mode.C1C3C2);
        return sm2.signHex(hexData, "xim");
    }

    public static boolean isValid(String hexPublicKey, String hexData, String hexSign) {
        SM2 sm2 = SmUtil.sm2(null, hexPublicKey);
        sm2.setMode(SM2Engine.Mode.C1C3C2);
        return sm2.verifyHex(hexData, hexSign, HexUtil.encodeHexStr("xim"));
    }

}
